#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>   // open
#include <unistd.h>  // write
#include <string.h>  // strlen
#include "../lzop.h"

#define BUFSIZE 64*1024

int main(int argc, char** argv) {
  lzop_stream s;
  unsigned char inbuf[BUFSIZE];
  unsigned char outbuf[BUFSIZE*2];
  int ifd, num;
  lzop_block b;
  char *fname;

  if( argc != 2 ) {
    fprintf(stderr, "ERROR: must provide one input filename\n");
    return 1;
  }

  fname = argv[1];

  ifd = open(fname, O_RDONLY);
  if( ifd < 0 ) {
    fprintf(stderr, "Error opening file for reading!\n");
    return 2;
  }

  // first, check magic number
  num = read(ifd, inbuf, sizeof(lzop_magic));
  if( ! check_magic(inbuf,num) ) {
    fprintf(stderr, "Magic number does not match\n");
    return 3;
  }
  fprintf(stderr, "Magic number... done\n");

  // read file header
  num = fread_lzop_header(&s, ifd);
  fprintf(stderr,"File header...");
  //lzop_print_header(&s,stderr);
  fprintf(stderr,"done\n");
  if( 0 == num ) {
    lzop_perror(&s, NULL);
    return 4;
  }

  // read compressed blocks
  b.c_buf = inbuf;
  b.c_len = BUFSIZE;
  num = fread_lzop_block(&s, ifd, &b);
  if( 0 == num ) {
    lzop_perror(&s, NULL);
    return 5;
  }
  while( b.d_len > 0 ) {
    // decompress to stdout
    fprintf(stderr,"Decompressing block... ");
    num = lzop_decompress(&s, &b, outbuf, BUFSIZE*2);
    fprintf(stderr,"%d bytes done\n", num);
    if( 0 == num ) {
      lzop_perror(&s, NULL);
      return 6;
    }
    if( write(STDOUT_FILENO,outbuf,num) != num ) {
      fprintf(stderr,"error writing to stdout!\n");
    }

    num = fread_lzop_block(&s, ifd, &b);
    if( 0 == num ) {
      lzop_perror(&s, NULL);
      return 7;
    }
  }

  return 0;
}
